package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.MdLcEquip;
import com.gqj.meter.domain.vo.MdLcEquipVo;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.service.IMdLcEquipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 终端Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdLcEquip", description = "终端")
@RestController
@RequestMapping("/meter/mdLcEquip")
public class MdLcEquipController extends BaseController {
    @Autowired
    private IMdLcEquipService mdLcEquipService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;

    /**
     * 查询终端列表
     */
    @ApiOperation("查询终端列表")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdLcEquip mdLcEquip) {
        startPage();
        List<MdLcEquip> list = mdLcEquipService.selectMdLcEquipList(mdLcEquip);
        return getDataTable(list);
    }

    /**
     * 导出终端列表
     */
    @ApiOperation("导出终端列表")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:export')")
    @Log(title = "终端", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdLcEquip mdLcEquip) {
        List<MdLcEquip> list = mdLcEquipService.selectMdLcEquipList(mdLcEquip);
        ExcelUtil<MdLcEquip> util = new ExcelUtil<MdLcEquip>(MdLcEquip.class);
        util.exportExcel(response, list, "终端数据");
    }

    /**
     * 获取终端详细信息
     */
    @ApiOperation("获取终端详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:query')")
    @GetMapping(value = "/{lcEquipId}")
    public AjaxResult getInfo(@PathVariable("lcEquipId") Long lcEquipId) {
        return success(mdLcEquipService.selectMdLcEquipByLcEquipId(lcEquipId));
    }

    /**
     * 新增终端
     */
    @ApiOperation("新增终端")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:add')")
    @Log(title = "终端", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdLcEquip mdLcEquip) {
        if (UserConstants.NOT_UNIQUE.equals(mdLcEquipService.checkRfidNoUnique(mdLcEquip))) {
            return AjaxResult.error("新增'" + mdLcEquip.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdLcEquipService.insertMdLcEquip(mdLcEquip));
    }

    /**
     * 修改终端
     */
    @ApiOperation("修改终端")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:edit')")
    @Log(title = "终端", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdLcEquip mdLcEquip) {
        if (null == mdLcEquip.getLcEquipId() || 0 == mdLcEquip.getLcEquipId()) {
            return AjaxResult.error("修改失败，终端ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdLcEquipService.checkRfidNoUnique(mdLcEquip))) {
            return AjaxResult.error("修改'" + mdLcEquip.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdLcEquipService.updateMdLcEquip(mdLcEquip));
    }

    /**
     * 删除终端
     */
    @ApiOperation("删除终端")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:remove')")
    @Log(title = "终端", businessType = BusinessType.DELETE)
    @DeleteMapping("/{lcEquipIds}")
    public AjaxResult remove(@PathVariable Long[] lcEquipIds) {
        //判断终端是否被引用
        for (int i = 0; i < lcEquipIds.length; i++) {
            MdLcEquip mdLcEquip = mdLcEquipService.selectMdLcEquipByLcEquipId(lcEquipIds[i]);
            //查看盘点单是否引用
            String serviceStatus = mdLcEquip.getServiceStatus();
            if (!"00".equals(serviceStatus) && !"01".equals(serviceStatus) && !"04".equals(serviceStatus)) {
                return AjaxResult.error("终端" + mdLcEquip.getRfidNo() + "的业务状态不允许删除！");
            }

            //查看出入库是否引用
            MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
            mdInTaskDetails.setRfidNo(mdLcEquip.getRfidNo());
            mdInTaskDetails.setIsComplete("0");
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
            if (mdInTaskDetailsList.size() > 0) {
                return AjaxResult.error("终端" + mdLcEquip.getRfidNo() + "入库任务中已经引用，无法删除！");
            }
        }
        return toAjax(mdLcEquipService.deleteMdLcEquipByLcEquipIds(lcEquipIds));
    }

    /**
     * 下载终端json文件
     */
    @ApiOperation("下载终端json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:downloadJsonMdLcEquip')")
    @GetMapping("/downloadJsonMdLcEquip")
    public AjaxResult downloadJsonMdLcEquip(MdLcEquip mdLcEquip) {
        List<MdLcEquip> mle = mdLcEquipService.selectMdLcEquipList(mdLcEquip);
        List<MdLcEquipVo> vos = StorageUtil.copyList(mle, MdLcEquipVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "终端数据" + orderNo);
        return AjaxResult.success(fileName + "终端数据" + orderNo);
    }

    /**
     * 导入终端execl文件
     */
    @ApiOperation("导入终端execl文件")
    @Log(title = "导入终端execl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:importDataLcEquip')")
    @PostMapping("/importDataLcEquip")
    public AjaxResult importDataLcEquip(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdLcEquip> util = new ExcelUtil<MdLcEquip>(MdLcEquip.class);
        List<MdLcEquip> mdLcEquipList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdLcEquipService.importDataLcEquip(mdLcEquipList, updateSupport, operName);
        return success(message);
    }

    @ApiOperation("下载终端模板")
    @PostMapping("/importTemplateMdLcEquip")
    @PreAuthorize("@ss.hasPermi('meter:mdLcEquip:importTemplateMdLcEquip')")
    public void importTemplateMdLcEquip(HttpServletResponse response) {
        ExcelUtil<MdLcEquip> util = new ExcelUtil<MdLcEquip>(MdLcEquip.class);
        util.importTemplateExcel(response, "终端数据");
    }
}
